3 * This is the MySQL database abstraction layer.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 namespace Wikimedia\Rdbms
;
28 use InvalidArgumentException
;
34 * Database abstraction object for MySQL.
35 * Defines methods independent on used MySQL extension.
41 abstract class DatabaseMysqlBase
extends Database
{
42 /** @var MysqlMasterPos */
43 protected $lastKnownReplicaPos;
44 /** @var string Method to detect replica DB lag */
45 protected $lagDetectionMethod;
46 /** @var array Method to detect replica DB lag */
47 protected $lagDetectionOptions = [];
48 /** @var bool bool Whether to use GTID methods */
49 protected $useGTIDs = false;
50 /** @var string|null */
51 protected $sslKeyPath;
52 /** @var string|null */
53 protected $sslCertPath;
54 /** @var string|null */
56 /** @var string|null */
58 /** @var string[]|null */
59 protected $sslCiphers;
60 /** @var string sql_mode value to send on connection */
62 /** @var bool Use experimental UTF-8 transmission encoding */
65 protected $defaultBigSelects = null;
67 /** @var string|null */
68 private $serverVersion = null;
70 private $insertSelectIsSafe = null;
71 /** @var stdClass|null */
72 private $replicationInfoRow = null;
74 // Cache getServerId() for 24 hours
75 const SERVER_ID_CACHE_TTL
= 86400;
77 /** @var float Warn if lag estimates are made for transactions older than this many seconds */
78 const LAG_STALE_WARN_THRESHOLD
= 0.100;
81 * Additional $params include:
82 * - lagDetectionMethod : set to one of (Seconds_Behind_Master,pt-heartbeat).
83 * pt-heartbeat assumes the table is at heartbeat.heartbeat
84 * and uses UTC timestamps in the heartbeat.ts column.
85 * (https://www.percona.com/doc/percona-toolkit/2.2/pt-heartbeat.html)
86 * - lagDetectionOptions : if using pt-heartbeat, this can be set to an array map to change
87 * the default behavior. Normally, the heartbeat row with the server
88 * ID of this server's master will be used. Set the "conds" field to
89 * override the query conditions, e.g. ['shard' => 's1'].
90 * - useGTIDs : use GTID methods like MASTER_GTID_WAIT() when possible.
91 * - insertSelectIsSafe : force that native INSERT SELECT is or is not safe [default: null]
92 * - sslKeyPath : path to key file [default: null]
93 * - sslCertPath : path to certificate file [default: null]
94 * - sslCAFile: path to a single certificate authority PEM file [default: null]
95 * - sslCAPath : parth to certificate authority PEM directory [default: null]
96 * - sslCiphers : array list of allowable ciphers [default: null]
97 * @param array $params
99 function __construct( array $params ) {
100 $this->lagDetectionMethod
= $params['lagDetectionMethod'] ??
'Seconds_Behind_Master';
101 $this->lagDetectionOptions
= $params['lagDetectionOptions'] ??
[];
102 $this->useGTIDs
= !empty( $params['useGTIDs' ] );
103 foreach ( [ 'KeyPath', 'CertPath', 'CAFile', 'CAPath', 'Ciphers' ] as $name ) {
105 if ( isset( $params[$var] ) ) {
106 $this->$var = $params[$var];
109 $this->sqlMode
= $params['sqlMode'] ??
null;
110 $this->utf8Mode
= !empty( $params['utf8Mode'] );
111 $this->insertSelectIsSafe
= isset( $params['insertSelectIsSafe'] )
112 ?
(bool)$params['insertSelectIsSafe'] : null;
114 parent
::__construct( $params );
120 public function getType() {
124 protected function open( $server, $user, $password, $dbName, $schema, $tablePrefix ) {
125 # Close/unset connection handle
128 $this->server
= $server;
130 $this->password
= $password;
132 $this->installErrorHandler();
134 $this->conn
= $this->mysqlConnect( $this->server
, $dbName );
135 } catch ( Exception
$ex ) {
136 $this->restoreErrorHandler();
139 $error = $this->restoreErrorHandler();
141 # Always log connection errors
142 if ( !$this->conn
) {
143 $error = $error ?
: $this->lastError();
144 $this->connLogger
->error(
145 "Error connecting to {db_server}: {error}",
146 $this->getLogContext( [
147 'method' => __METHOD__
,
151 $this->connLogger
->debug( "DB connection error\n" .
152 "Server: $server, User: $user, Password: " .
153 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
155 throw new DBConnectionError( $this, $error );
158 if ( strlen( $dbName ) ) {
159 $this->selectDomain( new DatabaseDomain( $dbName, null, $tablePrefix ) );
161 $this->currentDomain
= new DatabaseDomain( null, null, $tablePrefix );
164 // Tell the server what we're communicating with
165 if ( !$this->connectInitCharset() ) {
166 $error = $this->lastError();
167 $this->queryLogger
->error(
168 "Error setting character set: {error}",
169 $this->getLogContext( [
170 'method' => __METHOD__
,
171 'error' => $this->lastError(),
174 throw new DBConnectionError( $this, "Error setting character set: $error" );
177 // Abstract over any insane MySQL defaults
178 $set = [ 'group_concat_max_len = 262144' ];
179 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
180 if ( is_string( $this->sqlMode
) ) {
181 $set[] = 'sql_mode = ' . $this->addQuotes( $this->sqlMode
);
183 // Set any custom settings defined by site config
184 // (e.g. https://dev.mysql.com/doc/refman/4.1/en/innodb-parameters.html)
185 foreach ( $this->sessionVars
as $var => $val ) {
186 // Escape strings but not numbers to avoid MySQL complaining
187 if ( !is_int( $val ) && !is_float( $val ) ) {
188 $val = $this->addQuotes( $val );
190 $set[] = $this->addIdentifierQuotes( $var ) . ' = ' . $val;
194 // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
195 $success = $this->doQuery( 'SET ' . implode( ', ', $set ) );
197 $error = $this->lastError();
198 $this->queryLogger
->error(
199 'Error setting MySQL variables on server {db_server}: {error}',
200 $this->getLogContext( [
201 'method' => __METHOD__
,
205 throw new DBConnectionError( $this, "Error setting MySQL variables: $error" );
209 $this->opened
= true;
215 * Set the character set information right after connection
218 protected function connectInitCharset() {
219 if ( $this->utf8Mode
) {
220 // Tell the server we're communicating with it in UTF-8.
221 // This may engage various charset conversions.
222 return $this->mysqlSetCharset( 'utf8' );
224 return $this->mysqlSetCharset( 'binary' );
228 protected function doSelectDomain( DatabaseDomain
$domain ) {
229 if ( $domain->getSchema() !== null ) {
230 throw new DBExpectedError( $this, __CLASS__
. ": domain schemas are not supported." );
233 $database = $domain->getDatabase();
234 // A null database means "don't care" so leave it as is and update the table prefix
235 if ( $database === null ) {
236 $this->currentDomain
= new DatabaseDomain(
237 $this->currentDomain
->getDatabase(),
239 $domain->getTablePrefix()
245 if ( $database !== $this->getDBname() ) {
246 $sql = 'USE ' . $this->addIdentifierQuotes( $database );
247 $ret = $this->doQuery( $sql );
248 if ( $ret === false ) {
249 $error = $this->lastError();
250 $errno = $this->lastErrno();
251 $this->reportQueryError( $error, $errno, $sql, __METHOD__
);
255 // Update that domain fields on success (no exception thrown)
256 $this->currentDomain
= $domain;
262 * Open a connection to a MySQL server
264 * @param string $realServer
265 * @param string|null $dbName
266 * @return mixed Raw connection
267 * @throws DBConnectionError
269 abstract protected function mysqlConnect( $realServer, $dbName );
272 * Set the character set of the MySQL link
274 * @param string $charset
277 abstract protected function mysqlSetCharset( $charset );
280 * @param ResultWrapper|resource $res
281 * @throws DBUnexpectedError
283 public function freeResult( $res ) {
284 if ( $res instanceof ResultWrapper
) {
287 Wikimedia\
suppressWarnings();
288 $ok = $this->mysqlFreeResult( $res );
289 Wikimedia\restoreWarnings
();
291 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
298 * @param resource $res Raw result
301 abstract protected function mysqlFreeResult( $res );
304 * @param ResultWrapper|resource $res
305 * @return stdClass|bool
306 * @throws DBUnexpectedError
308 public function fetchObject( $res ) {
309 if ( $res instanceof ResultWrapper
) {
312 Wikimedia\
suppressWarnings();
313 $row = $this->mysqlFetchObject( $res );
314 Wikimedia\restoreWarnings
();
316 $errno = $this->lastErrno();
317 // Unfortunately, mysql_fetch_object does not reset the last errno.
318 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
319 // these are the only errors mysql_fetch_object can cause.
320 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
321 if ( $errno == 2000 ||
$errno == 2013 ) {
322 throw new DBUnexpectedError(
324 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
332 * Fetch a result row as an object
334 * @param resource $res Raw result
337 abstract protected function mysqlFetchObject( $res );
340 * @param IResultWrapper|resource $res
342 * @throws DBUnexpectedError
344 public function fetchRow( $res ) {
345 if ( $res instanceof ResultWrapper
) {
348 Wikimedia\
suppressWarnings();
349 $row = $this->mysqlFetchArray( $res );
350 Wikimedia\restoreWarnings
();
352 $errno = $this->lastErrno();
353 // Unfortunately, mysql_fetch_array does not reset the last errno.
354 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
355 // these are the only errors mysql_fetch_array can cause.
356 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
357 if ( $errno == 2000 ||
$errno == 2013 ) {
358 throw new DBUnexpectedError(
360 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
368 * Fetch a result row as an associative and numeric array
370 * @param resource $res Raw result
373 abstract protected function mysqlFetchArray( $res );
376 * @throws DBUnexpectedError
377 * @param ResultWrapper|resource $res
380 function numRows( $res ) {
381 if ( $res instanceof ResultWrapper
) {
384 Wikimedia\
suppressWarnings();
385 $n = !is_bool( $res ) ?
$this->mysqlNumRows( $res ) : 0;
386 Wikimedia\restoreWarnings
();
388 // Unfortunately, mysql_num_rows does not reset the last errno.
389 // We are not checking for any errors here, since
390 // there are no errors mysql_num_rows can cause.
391 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
392 // See https://phabricator.wikimedia.org/T44430
397 * Get number of rows in result
399 * @param resource $res Raw result
402 abstract protected function mysqlNumRows( $res );
405 * @param ResultWrapper|resource $res
408 public function numFields( $res ) {
409 if ( $res instanceof ResultWrapper
) {
413 return $this->mysqlNumFields( $res );
417 * Get number of fields in result
419 * @param resource $res Raw result
422 abstract protected function mysqlNumFields( $res );
425 * @param ResultWrapper|resource $res
429 public function fieldName( $res, $n ) {
430 if ( $res instanceof ResultWrapper
) {
434 return $this->mysqlFieldName( $res, $n );
438 * Get the name of the specified field in a result
440 * @param ResultWrapper|resource $res
444 abstract protected function mysqlFieldName( $res, $n );
447 * mysql_field_type() wrapper
448 * @param ResultWrapper|resource $res
452 public function fieldType( $res, $n ) {
453 if ( $res instanceof ResultWrapper
) {
457 return $this->mysqlFieldType( $res, $n );
461 * Get the type of the specified field in a result
463 * @param ResultWrapper|resource $res
467 abstract protected function mysqlFieldType( $res, $n );
470 * @param ResultWrapper|resource $res
474 public function dataSeek( $res, $row ) {
475 if ( $res instanceof ResultWrapper
) {
479 return $this->mysqlDataSeek( $res, $row );
483 * Move internal result pointer
485 * @param ResultWrapper|resource $res
489 abstract protected function mysqlDataSeek( $res, $row );
494 public function lastError() {
496 # Even if it's non-zero, it can still be invalid
497 Wikimedia\
suppressWarnings();
498 $error = $this->mysqlError( $this->conn
);
500 $error = $this->mysqlError();
502 Wikimedia\restoreWarnings
();
504 $error = $this->mysqlError();
507 $error .= ' (' . $this->server
. ')';
514 * Returns the text of the error message from previous MySQL operation
516 * @param resource|null $conn Raw connection
519 abstract protected function mysqlError( $conn = null );
521 protected function wasQueryTimeout( $error, $errno ) {
522 // https://dev.mysql.com/doc/refman/8.0/en/client-error-reference.html
523 // https://phabricator.wikimedia.org/T170638
524 return in_array( $errno, [ 2062, 3024 ] );
527 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
528 $this->nativeReplace( $table, $rows, $fname );
531 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
532 $row = $this->getReplicationSafetyInfo();
533 // For row-based-replication, the resulting changes will be relayed, not the query
534 if ( $row->binlog_format
=== 'ROW' ) {
537 // LIMIT requires ORDER BY on a unique key or it is non-deterministic
538 if ( isset( $selectOptions['LIMIT'] ) ) {
541 // In MySQL, an INSERT SELECT is only replication safe with row-based
542 // replication or if innodb_autoinc_lock_mode is 0. When those
543 // conditions aren't met, use non-native mode.
544 // While we could try to determine if the insert is safe anyway by
545 // checking if the target table has an auto-increment column that
546 // isn't set in $varMap, that seems unlikely to be worth the extra
549 in_array( 'NO_AUTO_COLUMNS', $insertOptions ) ||
550 (int)$row->innodb_autoinc_lock_mode
=== 0
555 * @return stdClass Process cached row
557 protected function getReplicationSafetyInfo() {
558 if ( $this->replicationInfoRow
=== null ) {
559 $this->replicationInfoRow
= $this->selectRow(
562 'innodb_autoinc_lock_mode' => '@@innodb_autoinc_lock_mode',
563 'binlog_format' => '@@binlog_format',
570 return $this->replicationInfoRow
;
574 * Estimate rows in dataset
575 * Returns estimated count, based on EXPLAIN output
576 * Takes same arguments as Database::select()
578 * @param string|array $table
579 * @param string|array $var
580 * @param string|array $conds
581 * @param string $fname
582 * @param string|array $options
583 * @param array $join_conds
586 public function estimateRowCount( $table, $var = '*', $conds = '',
587 $fname = __METHOD__
, $options = [], $join_conds = []
589 $conds = $this->normalizeConditions( $conds, $fname );
590 $column = $this->extractSingleFieldFromList( $var );
591 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
592 $conds[] = "$column IS NOT NULL";
595 $options['EXPLAIN'] = true;
596 $res = $this->select( $table, $var, $conds, $fname, $options, $join_conds );
597 if ( $res === false ) {
600 if ( !$this->numRows( $res ) ) {
605 foreach ( $res as $plan ) {
606 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
612 public function tableExists( $table, $fname = __METHOD__
) {
613 // Split database and table into proper variables as Database::tableName() returns
614 // shared tables prefixed with their database, which do not work in SHOW TABLES statements
615 list( $database, , $prefix, $table ) = $this->qualifiedTableComponents( $table );
616 $tableName = "{$prefix}{$table}";
618 if ( isset( $this->sessionTempTables
[$tableName] ) ) {
619 return true; // already known to exist and won't show in SHOW TABLES anyway
622 // We can't use buildLike() here, because it specifies an escape character
623 // other than the backslash, which is the only one supported by SHOW TABLES
624 $encLike = $this->escapeLikeInternal( $tableName, '\\' );
626 // If the database has been specified (such as for shared tables), use "FROM"
627 if ( $database !== '' ) {
628 $encDatabase = $this->addIdentifierQuotes( $database );
629 $query = "SHOW TABLES FROM $encDatabase LIKE '$encLike'";
631 $query = "SHOW TABLES LIKE '$encLike'";
634 return $this->query( $query, $fname )->numRows() > 0;
638 * @param string $table
639 * @param string $field
640 * @return bool|MySQLField
642 public function fieldInfo( $table, $field ) {
643 $table = $this->tableName( $table );
644 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
648 $n = $this->mysqlNumFields( $res->result
);
649 for ( $i = 0; $i < $n; $i++
) {
650 $meta = $this->mysqlFetchField( $res->result
, $i );
651 if ( $field == $meta->name
) {
652 return new MySQLField( $meta );
660 * Get column information from a result
662 * @param resource $res Raw result
666 abstract protected function mysqlFetchField( $res, $n );
669 * Get information about an index into an object
670 * Returns false if the index does not exist
672 * @param string $table
673 * @param string $index
674 * @param string $fname
675 * @return bool|array|null False or null on failure
677 public function indexInfo( $table, $index, $fname = __METHOD__
) {
678 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
679 # SHOW INDEX should work for 3.x and up:
680 # https://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
681 $table = $this->tableName( $table );
682 $index = $this->indexName( $index );
684 $sql = 'SHOW INDEX FROM ' . $table;
685 $res = $this->query( $sql, $fname );
693 foreach ( $res as $row ) {
694 if ( $row->Key_name
== $index ) {
699 return $result ?
: false;
706 public function strencode( $s ) {
707 return $this->mysqlRealEscapeString( $s );
714 abstract protected function mysqlRealEscapeString( $s );
716 public function addQuotes( $s ) {
717 if ( is_bool( $s ) ) {
718 // Parent would transform to int, which does not play nice with MySQL type juggling.
719 // When searching for an int in a string column, the strings are cast to int, which
720 // means false would match any string not starting with a number.
721 $s = (string)(int)$s;
723 return parent
::addQuotes( $s );
727 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
732 public function addIdentifierQuotes( $s ) {
733 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
734 // Remove NUL bytes and escape backticks by doubling
735 return '`' . str_replace( [ "\0", '`' ], [ '', '``' ], $s ) . '`';
739 * @param string $name
742 public function isQuotedIdentifier( $name ) {
743 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
746 public function getLag() {
747 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
748 return $this->getLagFromPtHeartbeat();
750 return $this->getLagFromSlaveStatus();
757 protected function getLagDetectionMethod() {
758 return $this->lagDetectionMethod
;
764 protected function getLagFromSlaveStatus() {
765 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
766 $row = $res ?
$res->fetchObject() : false;
767 // If the server is not replicating, there will be no row
768 if ( $row && strval( $row->Seconds_Behind_Master
) !== '' ) {
769 return intval( $row->Seconds_Behind_Master
);
778 protected function getLagFromPtHeartbeat() {
779 $options = $this->lagDetectionOptions
;
781 $currentTrxInfo = $this->getRecordedTransactionLagStatus();
782 if ( $currentTrxInfo ) {
783 // There is an active transaction and the initial lag was already queried
784 $staleness = microtime( true ) - $currentTrxInfo['since'];
785 if ( $staleness > self
::LAG_STALE_WARN_THRESHOLD
) {
786 // Avoid returning higher and higher lag value due to snapshot age
787 // given that the isolation level will typically be REPEATABLE-READ
788 $this->queryLogger
->warning(
789 "Using cached lag value for {db_server} due to active transaction",
790 $this->getLogContext( [
791 'method' => __METHOD__
,
793 'trace' => ( new RuntimeException() )->getTraceAsString()
798 return $currentTrxInfo['lag'];
801 if ( isset( $options['conds'] ) ) {
802 // Best method for multi-DC setups: use logical channel names
803 $data = $this->getHeartbeatData( $options['conds'] );
805 // Standard method: use master server ID (works with stock pt-heartbeat)
806 $masterInfo = $this->getMasterServerInfo();
807 if ( !$masterInfo ) {
808 $this->queryLogger
->error(
809 "Unable to query master of {db_server} for server ID",
810 $this->getLogContext( [
811 'method' => __METHOD__
815 return false; // could not get master server ID
818 $conds = [ 'server_id' => intval( $masterInfo['serverId'] ) ];
819 $data = $this->getHeartbeatData( $conds );
822 list( $time, $nowUnix ) = $data;
823 if ( $time !== null ) {
824 // @time is in ISO format like "2015-09-25T16:48:10.000510"
825 $dateTime = new DateTime( $time, new DateTimeZone( 'UTC' ) );
826 $timeUnix = (int)$dateTime->format( 'U' ) +
$dateTime->format( 'u' ) / 1e6
;
828 return max( $nowUnix - $timeUnix, 0.0 );
831 $this->queryLogger
->error(
832 "Unable to find pt-heartbeat row for {db_server}",
833 $this->getLogContext( [
834 'method' => __METHOD__
841 protected function getMasterServerInfo() {
842 $cache = $this->srvCache
;
843 $key = $cache->makeGlobalKey(
846 // Using one key for all cluster replica DBs is preferable
847 $this->getLBInfo( 'clusterMasterHost' ) ?
: $this->getServer()
851 return $cache->getWithSetCallback(
853 $cache::TTL_INDEFINITE
,
854 function () use ( $cache, $key, $fname ) {
855 // Get and leave a lock key in place for a short period
856 if ( !$cache->lock( $key, 0, 10 ) ) {
857 return false; // avoid master connection spike slams
860 $conn = $this->getLazyMasterHandle();
862 return false; // something is misconfigured
865 // Connect to and query the master; catch errors to avoid outages
867 $res = $conn->query( 'SELECT @@server_id AS id', $fname );
868 $row = $res ?
$res->fetchObject() : false;
869 $id = $row ?
(int)$row->id
: 0;
870 } catch ( DBError
$e ) {
874 // Cache the ID if it was retrieved
875 return $id ?
[ 'serverId' => $id, 'asOf' => time() ] : false;
881 * @param array $conds WHERE clause conditions to find a row
882 * @return array (heartbeat `ts` column value or null, UNIX timestamp) for the newest beat
883 * @see https://www.percona.com/doc/percona-toolkit/2.1/pt-heartbeat.html
885 protected function getHeartbeatData( array $conds ) {
886 // Query time and trip time are not counted
887 $nowUnix = microtime( true );
888 // Do not bother starting implicit transactions here
889 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
891 $whereSQL = $this->makeList( $conds, self
::LIST_AND
);
892 // Use ORDER BY for channel based queries since that field might not be UNIQUE.
893 // Note: this would use "TIMESTAMPDIFF(MICROSECOND,ts,UTC_TIMESTAMP(6))" but the
894 // percision field is not supported in MySQL <= 5.5.
896 "SELECT ts FROM heartbeat.heartbeat WHERE $whereSQL ORDER BY ts DESC LIMIT 1",
899 $row = $res ?
$res->fetchObject() : false;
901 $this->restoreFlags();
904 return [ $row ?
$row->ts
: null, $nowUnix ];
907 protected function getApproximateLagStatus() {
908 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
909 // Disable caching since this is fast enough and we don't wan't
910 // to be *too* pessimistic by having both the cache TTL and the
911 // pt-heartbeat interval count as lag in getSessionLagStatus()
912 return parent
::getApproximateLagStatus();
915 $key = $this->srvCache
->makeGlobalKey( 'mysql-lag', $this->getServer() );
916 $approxLag = $this->srvCache
->get( $key );
918 $approxLag = parent
::getApproximateLagStatus();
919 $this->srvCache
->set( $key, $approxLag, 1 );
925 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
926 if ( !( $pos instanceof MySQLMasterPos
) ) {
927 throw new InvalidArgumentException( "Position not an instance of MySQLMasterPos" );
930 if ( $this->getLBInfo( 'is static' ) === true ) {
931 return 0; // this is a copy of a read-only dataset with no master DB
932 } elseif ( $this->lastKnownReplicaPos
&& $this->lastKnownReplicaPos
->hasReached( $pos ) ) {
933 return 0; // already reached this point for sure
936 // Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
937 if ( $pos->getGTIDs() ) {
938 // Ignore GTIDs from domains exclusive to the master DB (presumably inactive)
939 $rpos = $this->getReplicaPos();
940 $gtidsWait = $rpos ? MySQLMasterPos
::getCommonDomainGTIDs( $pos, $rpos ) : [];
942 $this->queryLogger
->error(
943 "No GTIDs with the same domain between master ($pos) and replica ($rpos)",
944 $this->getLogContext( [
945 'method' => __METHOD__
,
949 return -1; // $pos is from the wrong cluster?
951 // Wait on the GTID set (MariaDB only)
952 $gtidArg = $this->addQuotes( implode( ',', $gtidsWait ) );
953 if ( strpos( $gtidArg, ':' ) !== false ) {
954 // MySQL GTIDs, e.g "source_id:transaction_id"
955 $res = $this->doQuery( "SELECT WAIT_FOR_EXECUTED_GTID_SET($gtidArg, $timeout)" );
957 // MariaDB GTIDs, e.g."domain:server:sequence"
958 $res = $this->doQuery( "SELECT MASTER_GTID_WAIT($gtidArg, $timeout)" );
961 // Wait on the binlog coordinates
962 $encFile = $this->addQuotes( $pos->getLogFile() );
963 $encPos = intval( $pos->getLogPosition()[$pos::CORD_EVENT
] );
964 $res = $this->doQuery( "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)" );
967 $row = $res ?
$this->fetchRow( $res ) : false;
969 throw new DBExpectedError( $this, "Replication wait failed: {$this->lastError()}" );
972 // Result can be NULL (error), -1 (timeout), or 0+ per the MySQL manual
973 $status = ( $row[0] !== null ) ?
intval( $row[0] ) : null;
974 if ( $status === null ) {
975 if ( !$pos->getGTIDs() ) {
976 // T126436: jobs programmed to wait on master positions might be referencing
977 // binlogs with an old master hostname; this makes MASTER_POS_WAIT() return null.
978 // Try to detect this case and treat the replica DB as having reached the given
979 // position (any master switchover already requires that the new master be caught
980 // up before the switch).
981 $replicationPos = $this->getReplicaPos();
982 if ( $replicationPos && !$replicationPos->channelsMatch( $pos ) ) {
983 $this->lastKnownReplicaPos
= $replicationPos;
987 } elseif ( $status >= 0 ) {
988 // Remember that this position was reached to save queries next time
989 $this->lastKnownReplicaPos
= $pos;
996 * Get the position of the master from SHOW SLAVE STATUS
998 * @return MySQLMasterPos|bool
1000 public function getReplicaPos() {
1001 $now = microtime( true ); // as-of-time *before* fetching GTID variables
1003 if ( $this->useGTIDs() ) {
1004 // Try to use GTIDs, fallbacking to binlog positions if not possible
1005 $data = $this->getServerGTIDs( __METHOD__
);
1006 // Use gtid_slave_pos for MariaDB and gtid_executed for MySQL
1007 foreach ( [ 'gtid_slave_pos', 'gtid_executed' ] as $name ) {
1008 if ( isset( $data[$name] ) && strlen( $data[$name] ) ) {
1009 return new MySQLMasterPos( $data[$name], $now );
1014 $data = $this->getServerRoleStatus( 'SLAVE', __METHOD__
);
1015 if ( $data && strlen( $data['Relay_Master_Log_File'] ) ) {
1016 return new MySQLMasterPos(
1017 "{$data['Relay_Master_Log_File']}/{$data['Exec_Master_Log_Pos']}",
1026 * Get the position of the master from SHOW MASTER STATUS
1028 * @return MySQLMasterPos|bool
1030 public function getMasterPos() {
1031 $now = microtime( true ); // as-of-time *before* fetching GTID variables
1034 if ( $this->useGTIDs() ) {
1035 // Try to use GTIDs, fallbacking to binlog positions if not possible
1036 $data = $this->getServerGTIDs( __METHOD__
);
1037 // Use gtid_binlog_pos for MariaDB and gtid_executed for MySQL
1038 foreach ( [ 'gtid_binlog_pos', 'gtid_executed' ] as $name ) {
1039 if ( isset( $data[$name] ) && strlen( $data[$name] ) ) {
1040 $pos = new MySQLMasterPos( $data[$name], $now );
1044 // Filter domains that are inactive or not relevant to the session
1046 $pos->setActiveOriginServerId( $this->getServerId() );
1047 $pos->setActiveOriginServerUUID( $this->getServerUUID() );
1048 if ( isset( $data['gtid_domain_id'] ) ) {
1049 $pos->setActiveDomain( $data['gtid_domain_id'] );
1055 $data = $this->getServerRoleStatus( 'MASTER', __METHOD__
);
1056 if ( $data && strlen( $data['File'] ) ) {
1057 $pos = new MySQLMasterPos( "{$data['File']}/{$data['Position']}", $now );
1066 * @throws DBQueryError If the variable doesn't exist for some reason
1068 protected function getServerId() {
1069 $fname = __METHOD__
;
1070 return $this->srvCache
->getWithSetCallback(
1071 $this->srvCache
->makeGlobalKey( 'mysql-server-id', $this->getServer() ),
1072 self
::SERVER_ID_CACHE_TTL
,
1073 function () use ( $fname ) {
1074 $res = $this->query( "SELECT @@server_id AS id", $fname );
1075 return intval( $this->fetchObject( $res )->id
);
1081 * @return string|null
1083 protected function getServerUUID() {
1084 return $this->srvCache
->getWithSetCallback(
1085 $this->srvCache
->makeGlobalKey( 'mysql-server-uuid', $this->getServer() ),
1086 self
::SERVER_ID_CACHE_TTL
,
1088 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'server_uuid'" );
1089 $row = $this->fetchObject( $res );
1091 return $row ?
$row->Value
: null;
1097 * @param string $fname
1100 protected function getServerGTIDs( $fname = __METHOD__
) {
1102 // Get global-only variables like gtid_executed
1103 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_%'", $fname );
1104 foreach ( $res as $row ) {
1105 $map[$row->Variable_name
] = $row->Value
;
1107 // Get session-specific (e.g. gtid_domain_id since that is were writes will log)
1108 $res = $this->query( "SHOW SESSION VARIABLES LIKE 'gtid_%'", $fname );
1109 foreach ( $res as $row ) {
1110 $map[$row->Variable_name
] = $row->Value
;
1117 * @param string $role One of "MASTER"/"SLAVE"
1118 * @param string $fname
1119 * @return string[] Latest available server status row
1121 protected function getServerRoleStatus( $role, $fname = __METHOD__
) {
1122 return $this->query( "SHOW $role STATUS", $fname )->fetchRow() ?
: [];
1125 public function serverIsReadOnly() {
1126 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'read_only'", __METHOD__
);
1127 $row = $this->fetchObject( $res );
1129 return $row ?
( strtolower( $row->Value
) === 'on' ) : false;
1133 * @param string $index
1136 function useIndexClause( $index ) {
1137 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
1141 * @param string $index
1144 function ignoreIndexClause( $index ) {
1145 return "IGNORE INDEX (" . $this->indexName( $index ) . ")";
1151 function lowPriorityOption() {
1152 return 'LOW_PRIORITY';
1158 public function getSoftwareLink() {
1159 // MariaDB includes its name in its version string; this is how MariaDB's version of
1160 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
1161 // in libmysql/libmysql.c).
1162 $version = $this->getServerVersion();
1163 if ( strpos( $version, 'MariaDB' ) !== false ||
strpos( $version, '-maria-' ) !== false ) {
1164 return '[{{int:version-db-mariadb-url}} MariaDB]';
1167 // Percona Server's version suffix is not very distinctive, and @@version_comment
1168 // doesn't give the necessary info for source builds, so assume the server is MySQL.
1169 // (Even Percona's version of mysql doesn't try to make the distinction.)
1170 return '[{{int:version-db-mysql-url}} MySQL]';
1176 public function getServerVersion() {
1177 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
1178 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
1179 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
1180 if ( $this->serverVersion
=== null ) {
1181 $this->serverVersion
= $this->selectField( '', 'VERSION()', '', __METHOD__
);
1183 return $this->serverVersion
;
1187 * @param array $options
1189 public function setSessionOptions( array $options ) {
1190 if ( isset( $options['connTimeout'] ) ) {
1191 $timeout = (int)$options['connTimeout'];
1192 $this->query( "SET net_read_timeout=$timeout" );
1193 $this->query( "SET net_write_timeout=$timeout" );
1198 * @param string &$sql
1199 * @param string &$newLine
1202 public function streamStatementEnd( &$sql, &$newLine ) {
1203 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
1204 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
1205 $this->delimiter
= $m[1];
1209 return parent
::streamStatementEnd( $sql, $newLine );
1213 * Check to see if a named lock is available. This is non-blocking.
1215 * @param string $lockName Name of lock to poll
1216 * @param string $method Name of method calling us
1220 public function lockIsFree( $lockName, $method ) {
1221 if ( !parent
::lockIsFree( $lockName, $method ) ) {
1222 return false; // already held
1225 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1226 $result = $this->query( "SELECT IS_FREE_LOCK($encName) AS lockstatus", $method );
1227 $row = $this->fetchObject( $result );
1229 return ( $row->lockstatus
== 1 );
1233 * @param string $lockName
1234 * @param string $method
1235 * @param int $timeout
1238 public function lock( $lockName, $method, $timeout = 5 ) {
1239 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1240 $result = $this->query( "SELECT GET_LOCK($encName, $timeout) AS lockstatus", $method );
1241 $row = $this->fetchObject( $result );
1243 if ( $row->lockstatus
== 1 ) {
1244 parent
::lock( $lockName, $method, $timeout ); // record
1248 $this->queryLogger
->info( __METHOD__
. " failed to acquire lock '{lockname}'",
1249 [ 'lockname' => $lockName ] );
1256 * https://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
1257 * @param string $lockName
1258 * @param string $method
1261 public function unlock( $lockName, $method ) {
1262 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1263 $result = $this->query( "SELECT RELEASE_LOCK($encName) as lockstatus", $method );
1264 $row = $this->fetchObject( $result );
1266 if ( $row->lockstatus
== 1 ) {
1267 parent
::unlock( $lockName, $method ); // record
1271 $this->queryLogger
->warning( __METHOD__
. " failed to release lock '$lockName'\n" );
1276 private function makeLockName( $lockName ) {
1277 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1278 // Newer version enforce a 64 char length limit.
1279 return ( strlen( $lockName ) > 64 ) ?
sha1( $lockName ) : $lockName;
1282 public function namedLocksEnqueue() {
1286 public function tableLocksHaveTransactionScope() {
1287 return false; // tied to TCP connection
1290 protected function doLockTables( array $read, array $write, $method ) {
1292 foreach ( $write as $table ) {
1293 $items[] = $this->tableName( $table ) . ' WRITE';
1295 foreach ( $read as $table ) {
1296 $items[] = $this->tableName( $table ) . ' READ';
1299 $sql = "LOCK TABLES " . implode( ',', $items );
1300 $this->query( $sql, $method );
1305 protected function doUnlockTables( $method ) {
1306 $this->query( "UNLOCK TABLES", $method );
1312 * @param bool $value
1314 public function setBigSelects( $value = true ) {
1315 if ( $value === 'default' ) {
1316 if ( $this->defaultBigSelects
=== null ) {
1317 # Function hasn't been called before so it must already be set to the default
1320 $value = $this->defaultBigSelects
;
1322 } elseif ( $this->defaultBigSelects
=== null ) {
1323 $this->defaultBigSelects
=
1324 (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__
);
1326 $encValue = $value ?
'1' : '0';
1327 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
1331 * DELETE where the condition is a join. MySql uses multi-table deletes.
1332 * @param string $delTable
1333 * @param string $joinTable
1334 * @param string $delVar
1335 * @param string $joinVar
1336 * @param array|string $conds
1337 * @param bool|string $fname
1338 * @throws DBUnexpectedError
1340 public function deleteJoin(
1341 $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
1344 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
1347 $delTable = $this->tableName( $delTable );
1348 $joinTable = $this->tableName( $joinTable );
1349 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1351 if ( $conds != '*' ) {
1352 $sql .= ' AND ' . $this->makeList( $conds, self
::LIST_AND
);
1355 $this->query( $sql, $fname );
1358 public function upsert(
1359 $table, array $rows, $uniqueIndexes, array $set, $fname = __METHOD__
1361 if ( $rows === [] ) {
1362 return true; // nothing to do
1365 if ( !is_array( reset( $rows ) ) ) {
1369 $table = $this->tableName( $table );
1370 $columns = array_keys( $rows[0] );
1372 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
1374 foreach ( $rows as $row ) {
1375 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
1377 $sql .= implode( ',', $rowTuples );
1378 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, self
::LIST_SET
);
1380 $this->query( $sql, $fname );
1386 * Determines how long the server has been up
1390 public function getServerUptime() {
1391 $vars = $this->getMysqlStatus( 'Uptime' );
1393 return (int)$vars['Uptime'];
1397 * Determines if the last failure was due to a deadlock
1401 public function wasDeadlock() {
1402 return $this->lastErrno() == 1213;
1406 * Determines if the last failure was due to a lock timeout
1410 public function wasLockTimeout() {
1411 return $this->lastErrno() == 1205;
1415 * Determines if the last failure was due to the database being read-only.
1419 public function wasReadOnlyError() {
1420 return $this->lastErrno() == 1223 ||
1421 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1424 public function wasConnectionError( $errno ) {
1425 return $errno == 2013 ||
$errno == 2006;
1428 protected function wasKnownStatementRollbackError() {
1429 $errno = $this->lastErrno();
1431 if ( $errno === 1205 ) { // lock wait timeout
1432 // Note that this is uncached to avoid stale values of SET is used
1433 $row = $this->selectRow(
1435 [ 'innodb_rollback_on_timeout' => '@@innodb_rollback_on_timeout' ],
1439 // https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
1440 // https://dev.mysql.com/doc/refman/5.5/en/innodb-parameters.html
1441 return $row->innodb_rollback_on_timeout ?
false : true;
1444 // See https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
1445 return in_array( $errno, [ 1022, 1062, 1216, 1217, 1137, 1146, 1051, 1054 ], true );
1449 * @param string $oldName
1450 * @param string $newName
1451 * @param bool $temporary
1452 * @param string $fname
1455 public function duplicateTableStructure(
1456 $oldName, $newName, $temporary = false, $fname = __METHOD__
1458 $tmp = $temporary ?
'TEMPORARY ' : '';
1459 $newName = $this->addIdentifierQuotes( $newName );
1460 $oldName = $this->addIdentifierQuotes( $oldName );
1461 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1463 return $this->query( $query, $fname, $this::QUERY_PSEUDO_PERMANENT
);
1467 * List all tables on the database
1469 * @param string|null $prefix Only show tables with this prefix, e.g. mw_
1470 * @param string $fname Calling function name
1473 public function listTables( $prefix = null, $fname = __METHOD__
) {
1474 $result = $this->query( "SHOW TABLES", $fname );
1478 foreach ( $result as $table ) {
1479 $vars = get_object_vars( $table );
1480 $table = array_pop( $vars );
1482 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1483 $endArray[] = $table;
1491 * @param string $tableName
1492 * @param string $fName
1493 * @return bool|ResultWrapper
1495 public function dropTable( $tableName, $fName = __METHOD__
) {
1496 if ( !$this->tableExists( $tableName, $fName ) ) {
1500 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1504 * Get status information from SHOW STATUS in an associative array
1506 * @param string $which
1509 private function getMysqlStatus( $which = "%" ) {
1510 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1513 foreach ( $res as $row ) {
1514 $status[$row->Variable_name
] = $row->Value
;
1521 * Lists VIEWs in the database
1523 * @param string|null $prefix Only show VIEWs with this prefix, eg.
1524 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1525 * @param string $fname Name of calling function
1529 public function listViews( $prefix = null, $fname = __METHOD__
) {
1530 // The name of the column containing the name of the VIEW
1531 $propertyName = 'Tables_in_' . $this->getDBname();
1533 // Query for the VIEWS
1534 $res = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1536 foreach ( $res as $row ) {
1537 array_push( $allViews, $row->$propertyName );
1540 if ( is_null( $prefix ) ||
$prefix === '' ) {
1544 $filteredViews = [];
1545 foreach ( $allViews as $viewName ) {
1546 // Does the name of this VIEW start with the table-prefix?
1547 if ( strpos( $viewName, $prefix ) === 0 ) {
1548 array_push( $filteredViews, $viewName );
1552 return $filteredViews;
1556 * Differentiates between a TABLE and a VIEW.
1558 * @param string $name Name of the TABLE/VIEW to test
1559 * @param string|null $prefix
1563 public function isView( $name, $prefix = null ) {
1564 return in_array( $name, $this->listViews( $prefix ) );
1567 protected function isTransactableQuery( $sql ) {
1568 return parent
::isTransactableQuery( $sql ) &&
1569 !preg_match( '/^SELECT\s+(GET|RELEASE|IS_FREE)_LOCK\(/', $sql );
1572 public function buildStringCast( $field ) {
1573 return "CAST( $field AS BINARY )";
1577 * @param string $field Field or column to cast
1580 public function buildIntegerCast( $field ) {
1581 return 'CAST( ' . $field . ' AS SIGNED )';
1585 * @return bool Whether GTID support is used (mockable for testing)
1587 protected function useGTIDs() {
1588 return $this->useGTIDs
;
1593 * @deprecated since 1.29
1595 class_alias( DatabaseMysqlBase
::class, 'DatabaseMysqlBase' );